import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    // 三数之和（* 去重）
    public List<List<Integer>> threeSum(int[] nums) {
        int len = nums.length;
        List<List<Integer>> ret = new ArrayList<>();
        // 判断是否存在三个数
        if(len < 3) {
            return ret;
        }
        // 对元素进行排序
        Arrays.sort(nums);
        for(int i = 0; i < len - 2; ) {
            int target = 0 - nums[i];
            int left = i + 1;
            int right = len - 1;
            while(left < right) {
                int sum = nums[left] + nums[right];
                if(sum > target) {
                    right--;
                } else if(sum < target) {
                    left++;
                } else {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[left]);
                    list.add(nums[right]);
                    ret.add(list);
                    // 继续找
                    left++;
                    right--;
                    // 去重
                    while(left < right && nums[left] == nums[left - 1]) {
                        left++;
                    }
                    while(left < right && nums[right] == right + 1) {
                        right--;
                    }
                }
            }
            // 去重
            i++;
            while(i < len && nums[i] == nums[i - 1]) {
                i++;
            }
        }
        return ret;
    }

    public static void main(String[] args) {
        int[] nums = {-1,0,1,2,-1,-4};
        Solution solution = new Solution();
        solution.threeSum(nums);
    }
}